package com.example.easyrulesimple.fastdfs;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 作者：liyuan
 * 时间：2024/5/20 18:06
 * 描述：
 **/
@RestController
@RequestMapping("/myfast")
@Slf4j
public class FastController {
    @Autowired
    private FastDfsSysFileServiceImpl fastDfsSysFileService;
    @PostMapping("/upload")
    public String upload(MultipartFile file) throws Exception {
        String s = fastDfsSysFileService.uploadFile(file);
        return s;
    }

    @Autowired
    private FastFileStorageClient storageClient;

    @GetMapping("/download")
    public ResponseEntity<byte[]> download(@RequestParam String filepath) throws IOException {
        StorePath storePath = StorePath.parseFromUrl(filepath);
        byte[] content =  storageClient.downloadFile(storePath.getGroup(), storePath.getPath(),
                new DownloadByteArray());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//        storePath.getFileName();
        headers.setContentDispositionFormData("attachment", "test.docx");
        headers.setContentLength(content.length);
        return new ResponseEntity<>(content, headers, HttpStatus.OK);
    }

}
